import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Card, message } from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import { articleService } from '../services/articleService';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import styled from '@emotion/styled';

const { TextArea } = Input;

const EditorContainer = styled.div`
  .ql-editor {
    min-height: 300px;
  }
`;

const ArticleEdit: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const isEdit = id !== undefined;

  useEffect(() => {
    if (isEdit) {
      loadArticle();
    }
  }, [id]);

  const loadArticle = async () => {
    try {
      setLoading(true);
      const article = await articleService.getArticle(Number(id));
      form.setFieldsValue({
        title: article.title,
        content: article.content,
        summary: article.summary,
      });
    } catch (error) {
      message.error('加载文章失败');
    } finally {
      setLoading(false);
    }
  };

  const onFinish = async (values: any) => {
    try {
      setLoading(true);
      if (isEdit) {
        await articleService.updateArticle(Number(id), values);
        message.success('更新文章成功');
      } else {
        await articleService.createArticle(values);
        message.success('创建文章成功');
      }
      navigate('/articles');
    } catch (error) {
      message.error(isEdit ? '更新文章失败' : '创建文章失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card title={isEdit ? '编辑文章' : '写文章'}>
      <Form
        form={form}
        layout="vertical"
        onFinish={onFinish}
      >
        <Form.Item
          name="title"
          label="标题"
          rules={[{ required: true, message: '请输入文章标题' }]}
        >
          <Input placeholder="请输入文章标题" />
        </Form.Item>

        <Form.Item
          name="summary"
          label="摘要"
          rules={[{ required: true, message: '请输入文章摘要' }]}
        >
          <TextArea
            placeholder="请输入文章摘要"
            autoSize={{ minRows: 2, maxRows: 6 }}
          />
        </Form.Item>

        <Form.Item
          name="content"
          label="内容"
          rules={[{ required: true, message: '请输入文章内容' }]}
        >
          <EditorContainer>
            <ReactQuill theme="snow" />
          </EditorContainer>
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading}>
            {isEdit ? '更新' : '发布'}
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={() => navigate('/articles')}>
            取消
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default ArticleEdit; 